package psn.polaris.init.impl;

import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.core.Appender;
import org.apache.logging.log4j.core.Logger;
import org.apache.logging.log4j.core.LoggerContext;
import org.apache.logging.log4j.core.appender.ConsoleAppender;
import org.apache.logging.log4j.core.config.AppenderRef;
import org.apache.logging.log4j.core.config.Configuration;
import org.apache.logging.log4j.core.config.LoggerConfig;
import org.apache.logging.log4j.core.layout.PatternLayout;
import org.springframework.stereotype.Component;
import psn.polaris.init.AbsPolarisOwnerStartProcess;

import java.nio.charset.StandardCharsets;
import java.util.Collection;

@Component
public class AbsPolarisLogStartProcess extends AbsPolarisOwnerStartProcess {

    public AbsPolarisLogStartProcess() {
        super(Integer.MIN_VALUE);
    }

    /**
     * 初始化执行方法
     */
    @Override
    public void processInit() {
        logger.info("日志注册开始");
        final LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
        final Configuration config = ctx.getConfiguration();
        // 设置输出格式
        final PatternLayout layout = PatternLayout.newBuilder()
                .withCharset(StandardCharsets.UTF_8)
                .withConfiguration(config)
                .withPattern("%d{yyyy-MM-dd HH:mm:ss:SSS}  %highlight{%-5level}{FATAL=white,ERROR=red,WARN=bg_#5792e6 fg_#eef26b bold,INFO=Green,DEBUG=Blue} %style{(%t)}{blue} %style{%c(%L)}{Yellow} %msg%n")
                .build();
        // 设置输出器
        final Appender appender = ConsoleAppender.newBuilder()
                .setName("Console")
                .setImmediateFlush(true)
                .setLayout(layout)
                .build();
        appender.start();
        config.addAppender(appender);
        // 创建日志对象配置
        AppenderRef ref = AppenderRef.createAppenderRef("Console", null, null);
        AppenderRef[] refs = new AppenderRef[]{ref};
        LoggerConfig loggerConfig = LoggerConfig.createLogger(
                false,
                Level.INFO,
                "Polaris-Console",
                null,
                refs,
                null,
                config,
                null
        );
        // 清空原格式
        ctx.getConfiguration().getAppenders().clear();
        // 加入新格式
        ctx.getConfiguration().addAppender(appender);
        Collection<Logger> loggerCollection = ctx.getLoggers();
        for (Logger oriLogger : loggerCollection) {
            oriLogger.addAppender(appender);
        }
        // 创建新日志输出路径
        config.addLogger("psn.polaris", loggerConfig);
        ctx.getRootLogger().addAppender(appender);
        ctx.updateLoggers(config);
        // 启动全部日志出输出
        ctx.start();
    }

}
